package com.webvihar.access2db.activities;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.webvihar.access2db.R;
import com.webvihar.access2db.asynctasks.A2DbAsyncWebRequestTask;
import com.webvihar.access2db.builders.RunSelectQueryBuilder;
import com.webvihar.access2db.model.SelectQueryResult;
import com.webvihar.access2db.model.Table;
import com.webvihar.access2db.model.TableDataItem;
import com.webvihar.access2db.model.TableRowItem;
import com.webvihar.access2db.restapi.A2DbRunSelectQueryRequest;
import com.webvihar.access2db.restapi.A2DbWebResult;
import com.webvihar.access2db.utils.PreferencesManager;

public class TableDataActivity extends BaseActivity implements OnClickListener{

	public static final String TABLE_DATA_OPERATION_TYPE_ADD = "Add";
	public static final String TABLE_DATA_OPERATION_TYPE_EDIT_DELETE = "Edit_Delete";
	
	private TableLayout outputTable;
	private List<View> rows;
	private List<TableRowItem> tableRows;
	private TextView titleTxt;
	private ImageButton addTableRecordBtn;
	private String tableName;
	
	/** Called when the activity is first created. */
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		setContentView(R.layout.tables_data);
		Bundle bundle = getIntent().getExtras();
		tableName = bundle.getString(KEY_TABLE_NAME);
		tableRow = null;
		tableHeaders = null;
		setTitleBar();
		initUI();
		executeTableQuery();
		setListeners();
	}
	
	private void setTitleBar() {
		titleTxt = (TextView) findViewById(R.id.title_txt);
		titleTxt.setText(getString(R.string.tables_data_txt));
		addTableRecordBtn = (ImageButton) findViewById(R.id.title_action_image_btn);
		addTableRecordBtn.setVisibility(View.VISIBLE);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		executeTableQuery();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.database_menu, menu);
		return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
		case R.id.menu_database_refresh:	
			executeTableQuery();
			break;
		case R.id.menu_database_query_editor:
			navigateToQueryEditor();
			break;
		default:
			break;
		}
		return true;
	}
	
	private void navigateToQueryEditor() {
		Intent intent = new Intent(TableDataActivity.this, QueryEditorActivity.class);
		startActivity(intent);
	}


	private void setListeners() {
		addTableRecordBtn.setOnClickListener(this);
	}

	private void executeTableQuery() {
		A2DbRunSelectQueryRequest request = new A2DbRunSelectQueryRequest();
		request.encoded = true;
		request.host = 	PreferencesManager.getString(getApplicationContext(), PREF_SESSION_HOST);
		request.port =  PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PORT);
		request.username = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_USERNAME);
		request.password = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PASSWORD);
		request.dbname = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_DBNAME);
		request.query = getQueryBuilder().getShowTableData(tableName);
		request.requestDelegate = new RunSelectQueryBuilder();
		new A2DbAsyncWebRequestTask(true, getApplicationContext(), runSelectQueryRequestHandler, getProgressDialog()).execute(request);
	}

	private Handler runSelectQueryRequestHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			@SuppressWarnings("unchecked")
			A2DbWebResult<SelectQueryResult> response = (A2DbWebResult<SelectQueryResult>) msg.obj;
			if(response == null) {
				showToast("Response is null");
				TableDataActivity.this.finish();
			} else if(response.entity == null) {
				showToast("Server not found...");
				TableDataActivity.this.finish();
			} else if(response.entity.result == null){
				showToast(response.entity.error+"");
				TableDataActivity.this.finish();
			} else {
				displayTableData(response.entity.result);
			}
		}
	};

	private void initUI() {
		outputTable = (TableLayout) findViewById(R.id.table_data_output_table);
		outputTable.setBackgroundColor(Color.GRAY);
	}

	private void displayTableData(Table table) {
		// remove previous data
		outputTable.removeAllViews();
		rows = new ArrayList<View>();
		tableRows = new ArrayList<TableRowItem>();
		// add headers to the table layout		
		TableRow row = new TableRow(this);
		row.setBackgroundColor(Color.GRAY);
		row.setPadding(2, 2, 2, 2);
		// store table headers in baseactivity in the form of List<Header>
		tableHeaders = Arrays.asList(table.headers);
		for(int i=0; i<table.headers.length; i++) {
			row.addView(getTableHeaderTextView(this, table.headers[i].title));
		}
		// add header to the table layout
		outputTable.addView(row);

		for(int i=0; i<table.data.length; i++) {
			row = new TableRow(this);
			row.setBackgroundColor(Color.GRAY);
			row.setPadding(2, 2, 2, 2);
			
			TableRowItem rowItem = new TableRowItem();
			List<TableDataItem> items = new ArrayList<TableDataItem>();
			for(int j=0; j<table.headers.length; j++) {
				row.addView(getTableDataTextView(this, (table.data[i][j] != null) ? table.data[i][j] : "Null"));	
				TableDataItem item = new TableDataItem();
				item.header = table.headers[j];
				item.data = table.data[i][j];
				items.add(item);
			}
			rowItem.items = items;
			tableRows.add(rowItem);
			row.setOnClickListener(this);
			outputTable.addView(row);
			rows.add(row);
		}
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.title_action_image_btn:
			tableRow = null;
			intent = new Intent(TableDataActivity.this, TableDataOperationActivity.class);
			intent.putExtra(KEY_TABLE_DATA_NAVIGATION_MODE, TABLE_DATA_OPERATION_TYPE_ADD);
			startActivity(intent);
			break;
		default:
			v.setBackgroundColor(Color.LTGRAY);
			for(int i=0; i<rows.size(); i++) {
				if(v == rows.get(i)) {
					TableRowItem rowItem = tableRows.get(i);
					tableRow = rowItem;
				}
			}
			intent = new Intent(TableDataActivity.this, TableDataOperationActivity.class);
			intent.putExtra(KEY_TABLE_DATA_NAVIGATION_MODE, TABLE_DATA_OPERATION_TYPE_EDIT_DELETE);
			startActivity(intent);
			break;
		}
	}
}
